import socket
import json
import datetime
import tcp_add_pb2
from google.protobuf import json_format
def xlh():
    dict1 = {}
    send_name = input("姓名:")
    send_content = input("内容:")
    send_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    dict1["name"] = send_name
    dict1["time"] = send_time
    dict1["show"] = send_content
    # 将json转换为protobuf格式
    pbStringResponse = json_format.Parse(json.dumps(dict1), tcp_add_pb2.param())
    return pbStringResponse.SerializeToString()

if __name__ == '__main__':
    # 1.创建tcp服务端套接字
    tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    # 2.绑定端口号

    tcp_server_socket.bind(("", 9910))
    # 3.设置监听

    tcp_server_socket.listen(128)
    # 4.等待接收客户端的连接请求

    new_client, ip_port = tcp_server_socket.accept()

    print("端口号", ip_port)
    # 5.接收客户端数据
    # 收发信息都使用新的套接字
    while True:
        recv_data = new_client.recv(1024)
        tmessage = tcp_add_pb2.param()
        # 将信息反序列化
        tmessage.ParseFromString(recv_data)
        m_name = tmessage.name
        m_time = tmessage.time
        m_show = tmessage.show
        print(f'姓名:{m_name} 在{m_time}时说{m_show}')

        a = xlh()
        # 将数据传输
        new_client.send(a)

    # 关闭服务端和客户端的套接字,表示和客户端停止通信
    new_client.close()
    # 7.关闭服务端套接字,表示不再等待接收客户端的连接请求
    tcp_server_socket.close()
